package com.bigdata;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * description
 *
 * @author Cyber
 * <p> Created By 2025/3/15
 * @version 1.0
 */
@Slf4j
public class HiveSql {
    // JDBC 驱动类名
    private static final String DRIVER_NAME = "org.apache.hive.jdbc.HiveDriver";
    // HiveServer2 连接地址 (默认端口10000)
    private static final String CONNECTION_URL = "jdbc:hive2://master:10000";
    private static final String USERNAME = "lifangyu";
    private static final String PASSWORD = ""; // 如果不需要密码可留空

    private static final ExecutorService queryExecutor = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        try (java.sql.Connection conn = getConnection();
             Statement stmt = conn.createStatement()) {
            // 示例 SQL 执行
            String sql1 = "use catalog `mycatalog`";
            stmt.execute(sql1);
            String sql2 = "create database hive_db";
            stmt.execute(sql2);
            String sql3 = "use hive_db";
            stmt.execute(sql3);
            String sql4 = "create table hive_table(id int, name string)";
            stmt.execute(sql4);
            String sql5 = "insert into hive_table values(1, 'test')";
            stmt.execute(sql5);
            String sql6 = "insert into hive_table values(2, 'jame')";
            stmt.execute(sql6);
            String sql7 = "insert into hive_table values(3, 'java')";
            stmt.execute(sql7);
            String sql8 = "select * from hive_table";
            // 执行 DDL
            stmt.execute(sql8);
            log.info("表创建/校验成功");
            // 执行查询
            try (java.sql.ResultSet rs = stmt.executeQuery(sql2)) {
                // 获取元数据信息
                java.sql.ResultSetMetaData meta = rs.getMetaData();
                int columnCount = meta.getColumnCount();

                // 打印结果头
                StringBuilder header = new StringBuilder();
                for (int i = 1; i <= columnCount; i++) {
                    header.append(meta.getColumnName(i)).append("\t|");
                }
                log.info(header.toString());

                // 打印结果数据
                while (rs.next()) {
                    StringBuilder row = new StringBuilder();
                    for (int i = 1; i <= columnCount; i++) {
                        row.append(rs.getString(i)).append("\t|");
                    }
                    log.info(row.toString());
                }
            }
        } catch (Exception e) {
            log.error("SQL执行异常", e);
        }
    }

    private static Connection getConnection() throws SQLException {
        try {
            Class.forName(DRIVER_NAME);
        } catch (ClassNotFoundException e) {
            throw new SQLException("Hive驱动加载失败", e);
        }
        return DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD);
    }

    private void query(String sql) throws java.sql.SQLException {
        String paramSql = "SELECT * FROM table WHERE name = ?";
        try (PreparedStatement pstmt = getConnection().prepareStatement(paramSql)) {
            pstmt.setString(1, "test");
            java.sql.ResultSet rs = pstmt.executeQuery();
            // 处理结果...
        }
    }

    private void queryAsync() {
        CompletableFuture.runAsync(() -> {
            try (Connection conn = getConnection();
                 Statement stmt = conn.createStatement()) {
                //获取查询日志
                stmt.execute("SET hive.query.log.location=/Users/lifangyu/Documents/project/bigdata/bigdata-project/logs/hive_query_logs");
                java.sql.ResultSet rs = stmt.executeQuery("SELECT version() ");
                // 处理结果...

            } catch (Exception e) {
                log.error("异步查询异常", e);
            }
        }, queryExecutor);
        log.info("非阻塞执行，继续其他逻辑...");
    }
}

